package com.cloudcc.mobile.dao.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.SystemClock;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.ChatUserInfoEvent;
import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.EventList.MenuFillEvent;
import com.cloudcc.cloudframe.bus.EventList.ServerUrlEvent;
import com.cloudcc.cloudframe.bus.EventList.UpdateUserEvent;
import com.cloudcc.cloudframe.model.param.UpdateUserParam;
import com.cloudcc.cloudframe.model.param.UserInfoParam;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.net.async.GsonHttpResponseHandler;
import com.cloudcc.cloudframe.net.model.BaseNetModel;
import com.cloudcc.cloudframe.net.model.ChatUserPopj;
import com.cloudcc.cloudframe.net.model.LoginRequestModel;
import com.cloudcc.cloudframe.net.model.MenuPopj;
import com.cloudcc.cloudframe.net.model.UrlRequestModel;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.mobile.AppConfig;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.dao.BaseEngine;
import com.cloudcc.mobile.dao.UserEngine;
import com.cloudcc.mobile.database.LoginDBOpenHelper;
import com.cloudcc.mobile.database.LoginDBUser.Users;
import com.cloudcc.mobile.entity.LoginDBModel;
import com.cloudcc.mobile.entity.webview.AppURL;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.loopj.android.http.RequestParams;

public class UserEngineImpl extends BaseEngine implements UserEngine {
	private SQLiteDatabase db;
	private LoginDBOpenHelper dbOpenHelper;
	private LiteOrm liteOrm;

	public UserEngineImpl() {
		super();
	}

	public UserEngineImpl(Context context) {
		liteOrm = LiteOrm.newSingleInstance(context, AppConfig.DB_LOGIN);
		liteOrm.setDebugged(AppConfig.DEVELOPER_MODE);

		// old
		this.dbOpenHelper = new LoginDBOpenHelper(context);
		establishDb();
	}

	/**
	 * 登录
	 */
	@Override
	public String login(String name, String pwd) {
		String result = "";
		try {
			String url = UrlTools.url + UrlTools.loginpath + "userName=" + name
					+ "&password=" + pwd;
			result = NetWork.get(url.trim());
		} catch (Exception e) {
			Tools.handle(e);
		}
		return result;
	}

	@Override
	public String getAppUrl(String username) {
		String result = "";
		try {
			String Data = URLEncoder.encode(username, "utf-8");
			String url = "http://ccws.cloudcc.com/distributor.action?serviceName=getAppURL&data="
					+ Data;
			result = NetWork.get(url.trim());
		} catch (UnsupportedEncodingException e) {
			Tools.handle(e);
		}
		return result;

	}

	// 数据库操作--------------------------------------------------------------------------------------------------------------
	/** * 打开数据库 */
	@Override
	public void establishDb() {
		if (this.db == null) {
			this.db = this.dbOpenHelper.getWritableDatabase();
		}
	}

	/** * 插入一条记录 * @return 插入记录的id -1表示插入不成功 * */
	@Override
	public long insertOrUpdate(String userName, String password) {
		boolean isUpdate = false;
		String[] usernames = queryAllUserName();
		for (int i = 0; i < usernames.length; i++) {
			if (userName.equals(usernames[i])) {
				isUpdate = true;
				break;
			}
		}
		long id = -1;
		if (isUpdate) {
			id = update(userName, password);
		} else {
			if (db != null) {
				ContentValues values = new ContentValues();
				values.put(Users.USERNAME, userName);
				values.put(Users.PASSWORD, password);
				id = db.insert(LoginDBOpenHelper.USER_TABLE_NAME, null, values);
			}
		}
		return id;
	}

	/** *更新一条记录 */
	@Override
	public long update(String username, String password) {
		ContentValues values = new ContentValues();
		values.put(Users.USERNAME, username);
		values.put(Users.PASSWORD, password);
		long id = db.update(LoginDBOpenHelper.USER_TABLE_NAME, values,
				Users.USERNAME + " = '" + username + "'", null);
		return id;
	}

	/** * 根据用户名查询密码 */
	@Override
	public String queryPasswordByName(String username) {
		String sql = "select * from " + LoginDBOpenHelper.USER_TABLE_NAME
				+ " where " + Users.USERNAME + " = '" + username + "'";
		Cursor cursor = db.rawQuery(sql, null);
		String password = "";
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			password = cursor.getString(cursor.getColumnIndex(Users.PASSWORD));
		}
		cursor.close();
		return password;
	}

	/** * 记住密码选项框是否被选中 */
	@Override
	public int queryIsSavedByName(String username) {
		return 0;
	}

	/** * 自动登录选项框是否被选中 */
	@Override
	public int queryIsAutoByName(String username) {
		return 0;
	}

	/** * 查询所有用户名 */
	@Override
	public String[] queryAllUserName() {
		if (db != null) {
			Cursor cursor = db.query(LoginDBOpenHelper.USER_TABLE_NAME, null,
					null, null, null, null, null);
			int count = cursor.getCount();
			String[] userNames = new String[count];
			if (count > 0) {
				cursor.moveToFirst();
				for (int i = 0; i < count; i++) {
					userNames[i] = cursor.getString(cursor
							.getColumnIndex(Users.USERNAME));
					cursor.moveToNext();
				}
			}
			cursor.close();
			return userNames;
		} else {
			return new String[0];
		}
	}

	/** * 关闭数据库 */
	@Override
	public void cleanup() {
		if (this.db != null) {
			this.db.close();
			this.db = null;
		}
	}

	@Override
	public void login_w(String name, String pwd,boolean isMD5, final LoginEvent event) {
		
		//重置 网络
		AsyncClient.getInstance().clear(AppContext.getInstance());
		
		RequestParams params = new RequestParams();
		params.put("serviceName", "clogin");
		params.put("userName", name);
		params.put("password", pwd);
		params.put("isMD5", isMD5);
		AsyncClient.getInstance().post(
				UrlManager.getInterfaceUrl(),
				params,
				new GsonHttpResponseHandler<LoginRequestModel>(
						LoginRequestModel.class, event) {
					public void onSuccess(LoginRequestModel t) {
						RunTimeManager.getInstance().setLoginTime(
								SystemClock.elapsedRealtime());
						event.setOk(true);
						event.setData(t);
						EventEngine.post(event);
					};
				});
	}

	@Override
	public void getAppUrl_w(String username, ServerUrlEvent event) {
		AppURL url = new AppURL();
		url.setUsername(username);
		String data = GsonUtil.Object2Json(url);
		RequestParams params = new RequestParams();
		params.put("serviceName", "getAppURL");
		params.put("data", data);
		AsyncClient.getInstance().post(
				UrlManager.SERVER + "/distributor.action",
				params,
				new GsonHttpResponseHandler<UrlRequestModel>(
						UrlRequestModel.class, event));
	}

	@Override
	public void getModules(MenuFillEvent event) {
		RequestParams params = new RequestParams();
		params.put("serviceName", "getAppAndTabList");
		params.put("binding", RunTimeManager.getInstance().getServerBinding());

		AsyncClient.getInstance().post(
				UrlManager.APP_UR + "/distributor.action", params,
				new GsonHttpResponseHandler<MenuPopj>(MenuPopj.class, event));
	}

	@Override
	public void getChatUserInfo(UserInfoParam param, ChatUserInfoEvent event) {
		String data = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", "getChatterUserInfo");
		params.put("data", data);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());

		AsyncClient.getInstance().post(
				UrlManager.getInterfaceUrl(),
				params,
				new GsonHttpResponseHandler<ChatUserPopj>(ChatUserPopj.class,
						event));
	}

	@Override
	public void updateUser(UpdateUserParam param, UpdateUserEvent event) {
		String data = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", "updateChatterUserInfo");
		params.put("data", data);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance().post(
				UrlManager.getInterfaceUrl(),
				params,
				new GsonHttpResponseHandler<BaseNetModel>(BaseNetModel.class,
						event));
	}

	@Override
	public boolean insertOrUpdate(LoginDBModel login) {
		return isUpdateOk(liteOrm.save(login));
	}

	@Override
	public boolean delete(String userName) {
		WhereBuilder builder =new WhereBuilder(LoginDBModel.class);
		builder.where(LoginDBModel.COL_USERNAME+" LIKE ? ", new String[]{userName});
		int delete = liteOrm.delete(builder);
		return delete > 0;
	}

	@Override
	public String getPassword(String userName) {

		QueryBuilder builder = new QueryBuilder(LoginDBModel.class);
		builder.where(LoginDBModel.COL_USERNAME + " LIKE ?", new String[] { "%"
				+ userName + "%" });
		ArrayList<LoginDBModel> result = liteOrm.<LoginDBModel> query(builder);

		if (ListUtils.isEmpty(result)) {
			return "";
		}
		return result.get(0).password;

	}

	@Override
	public List<LoginDBModel> getAll() {
		QueryBuilder builder = new QueryBuilder(LoginDBModel.class);
		builder.limit("10");
		builder.appendOrderDescBy(LoginDBModel.COL_LASTLOGIN);
		ArrayList<LoginDBModel> result = liteOrm.query(builder);
		return result;
	}

}
